//
//  UIImage+PP.m
//  pickpic
//
//  Created by Jinxiao on 10/15/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "UIImage+PP.h"

@implementation UIImage (PP)

- (NSData *)dataByCompressingToConstrainedSize:(NSUInteger)constrainedSize {
    NSData *data = UIImagePNGRepresentation(self);

    if(data.length <= constrainedSize) {
        return data;
    }

    CGFloat level = 1;

    data = UIImageJPEGRepresentation(self, level);

    while(data.length > constrainedSize && level > 0) {
        level -= 0.1;
        data = UIImageJPEGRepresentation(self, level);
    }

    UIImage *croppedImage = [self resizedImageByConstranedSize:CGSizeMake(self.size.width/2, self.size.height/2)];

    level = 1;

    data = UIImageJPEGRepresentation(croppedImage, level);

    while(data.length > constrainedSize && level > 0) {
        level -= 0.1;
        data = UIImageJPEGRepresentation(croppedImage, level);
    }

    if(data.length <= constrainedSize) {
        return data;
    }

    return nil;
}

@end
